package org.example.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.example.common.LoginUser;
import org.example.common.Token;
import org.example.entity.Menu;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.entity.vo.LoginVo;
import org.example.mapper.UserMapper;
import org.example.redis.RedisUtils;
import org.example.service.IMenuService;
import org.example.service.IRoleService;
import org.example.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.LoginException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static org.example.common.Constants.CACHE_PREFIX_TOKEN;

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private PermssionImpl permssion;

    @Override
    @SneakyThrows
    public Token login(LoginVo loginVo) throws LoginException {
        User user=getBaseMapper().selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,loginVo.getUsername()));
        if(user == null){
            throw new LoginException("用户不存在");
        }
        if(!user.getPassword().equals(loginVo.getPassword())){
            throw new LoginException("密码不正确");
        }
        String uuid= UUID.randomUUID().toString();
        LoginUser loginUser = new LoginUser();
        loginUser.setNickname(user.getNickName());
        loginUser.setUsername(user.getUserName());
        PermssionImpl.Perms perms = permssion.getPerms(user);
        loginUser.setPermsList(perms.getPermsLsit());
        loginUser.setRoleKeyList(perms.getRoleKeys());
        redisUtils.set(CACHE_PREFIX_TOKEN + uuid,new ObjectMapper().writeValueAsString(loginUser),1800);
        //返回token
        Token token=new Token();
        token.setToken(uuid);
        return token;
    }

    @Override
    public void logout(String token) {
        redisUtils.del(CACHE_PREFIX_TOKEN + token);
    }
}
